<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryRef"
      :inline="true"
      v-show="showSearch"
      label-width="80px"
    >
      <!-- <el-form-item label="用户名" prop="userName">
                <el-input v-model="queryParams.userName" placeholder="请输入用户名" clearable @keyup.enter="handleQuery" />
            </el-form-item> -->
      <el-form-item label="支付金额" prop="paymoney">
        <el-input
          v-model="queryParams.paymoney"
          placeholder="请输入支付金额"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="开始时间" prop="orderStart">
        <el-date-picker
          clearable
          v-model="queryParams.orderStart"
          type="date"
          value-format="YYYY-MM-DD"
          placeholder="请选择订单开始时间"
        >
        </el-date-picker>
      </el-form-item>

      <el-form-item label="服务名称" prop="serviceName">
        <el-input
          v-model="queryParams.serviceName"
          placeholder="请输入服务名称"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <!-- <el-form-item label="优惠券ID" prop="couponId">
                <el-input v-model="queryParams.couponId" placeholder="请输入优惠券ID" clearable @keyup.enter="handleQuery" />
            </el-form-item> -->
      <el-form-item label="支付时间" prop="payTime">
        <el-date-picker
          clearable
          v-model="queryParams.payTime"
          type="date"
          value-format="YYYY-MM-DD"
          placeholder="请选择支付时间"
        >
        </el-date-picker>
      </el-form-item>

      <el-form-item label="技师编号" prop="employeeId">
        <el-input
          v-model="queryParams.employeeId"
          placeholder="请输入技师编号"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <!-- <el-col :span="1.5">
                <el-button type="primary" plain icon="Plus" @click="handleAdd"
                    v-hasPermi="['shop:order:add']">新增</el-button>
            </el-col> -->

      <!-- <el-col :span="1.5">
                <el-button type="warning" plain icon="Download" @click="handleExport"
                    v-hasPermi="['shop:order:export']">导出</el-button>
            </el-col> -->
      <right-toolbar
        v-model:showSearch="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <el-table
      v-loading="loading"
      :data="orderList"
      @selection-change="handleSelectionChange"
      empty-text="暂无订单"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="订单编号" align="center" prop="orderId" />
      <!-- <el-table-column label="用户名" align="center" prop="userName" /> -->
      <el-table-column label="支付金额" align="center" prop="paymoney" />
      <!-- <el-table-column label="付款类型" align="center" prop="paymentType" width="100" /> -->
      <el-table-column
        label="订单开始时间"
        align="center"
        prop="orderStart"
        width="180"
      >
        <template #default="scope">
          <span>{{ parseTime(scope.row.orderStart, "{y}-{m}-{d}") }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="订单结束时间"
        align="center"
        prop="orderOver"
        width="180"
      >
        <template #default="scope">
          <span>{{ parseTime(scope.row.orderOver, "{y}-{m}-{d}") }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="订单暂停时间"
        align="center"
        prop="orderPause"
        width="180"
      >
        <template #default="scope">
          <span>{{ parseTime(scope.row.orderPause, "{y}-{m}-{d}") }}</span>
        </template>
      </el-table-column>
      <el-table-column label="服务名称" align="center" prop="serviceName" />
      <el-table-column label="订单状态" align="center" prop="orderStatus" />
      <el-table-column label="优惠券编号" align="center" prop="couponId" width="100"/>
      <el-table-column
        label="优惠券金额"
        align="center"
        prop="couponPrice"
        width="180"
      />
      <el-table-column label="支付状态" align="center" prop="payStatus" />
      <el-table-column
        label="支付时间"
        align="center"
        prop="payTime"
        width="180"
      >
        <template #default="scope">
          <span>{{ parseTime(scope.row.payTime, "{y}-{m}-{d}") }}</span>
        </template>
      </el-table-column>
      <el-table-column label="店铺名" align="center" prop="shopName" />
      <el-table-column label="技师编号" align="center" prop="employeeId" />
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
        width="280"
      >
        <template #default="scope">
          <el-button
            link
            type="primary"
            icon="Delete"
            v-show="scope.row.payStatus == '未支付'"
            >去付款</el-button
          >
          <el-button
            link
            type="primary"
            icon="Edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['shop:order:edit']"
            >修改</el-button
          >
          <el-button
            link
            type="primary"
            icon="Delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['shop:order:remove']"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改订单对话框 -->
<el-dialog :title="title" v-model="open" width="1000px" append-to-body>
  <el-form ref="orderRef" :model="form" :rules="rules" label-width="100px">
    <!-- 服务选择 -->
    <el-form-item label="服务列表" prop="serviceName">
      <el-table
        :data="serviceTable"
        style="width: 100%"
        @selection-change="handleServiceChange"
        height="300"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column label="名称" prop="serviceName" width="120" />
        <el-table-column label="图片" align="center" width="120">
          <template #default="{ row }">
            <el-image
              v-if="row.servicePic"
              :src="row.servicePic"
              style="width: 60px; height: 60px"
              :preview-src-list="[row.servicePic]"
            />
          </template>
        </el-table-column>
        <el-table-column prop="serviceDetails" label="项目" show-overflow-tooltip />
        <el-table-column prop="serviceTime" label="时长(分钟)" width="100" />
        <el-table-column prop="servicePrice" label="价格(元)" width="100" />
      </el-table>
    </el-form-item>

    <!-- 优惠券选择 -->
    <el-form-item label="优惠券" prop="couponId">
      <el-select 
        v-model="form.couponId" 
        placeholder="请选择优惠券"
        style="width: 100%"
      >
        <el-option
          v-for="item in couponList"
          :key="item.couponId"
          :label="`优惠券 ${item.couponPrice}元`"
          :value="item.couponId"
        >
          <div class="coupon-option">
            <el-image
              :src="item.couponPic"
              style="width: 40px; height: 40px"
            />
            <span class="coupon-price">￥{{ item.couponPrice }}</span>
          </div>
        </el-option>
      </el-select>
    </el-form-item>

    <!-- 技师选择 -->
    <el-form-item label="技师" prop="employeeId">
      <el-table
        :data="employeeList"
        style="width: 100%"
        highlight-current-row
        @current-change="handleEmployeeChange"
        height="250"
      >
        <el-table-column prop="employeeId" label="编号" width="100" />
        <el-table-column prop="employeeName" label="姓名" width="120" />
        <el-table-column label="照片" align="center" width="120">
          <template #default="{ row }">
            <el-image
              v-if="row.employeePic"
              :src="row.employeePic"
              style="width: 60px; height: 60px"
              :preview-src-list="[row.employeePic]"
            />
          </template>
        </el-table-column>
        <el-table-column prop="employeeStatus" label="状态" width="100" />
      </el-table>
    </el-form-item>

    <!-- 时间选择 -->
    <el-form-item label="服务时间" required>
      <div class="time-picker-container">
        <el-date-picker
          v-model="selectedDate"
          type="date"
          :disabled-date="disabledDate"
          placeholder="选择日期"
          style="width: 180px; margin-right: 16px"
        />
        <el-time-picker
          v-model="selectedTime"
          :disabled-hours="disabledHours"
          :disabled-minutes="disabledMinutes"
          format="HH:mm"
          placeholder="选择时间"
          style="width: 180px"
        />
      </div>
    </el-form-item>
  </el-form>

  <template #footer>
    <div class="dialog-footer">
      <el-button type="primary" @click="submitForm">确 定</el-button>
      <el-button @click="cancel">取 消</el-button>
    </div>
  </template>
</el-dialog>
  </div>
</template>

<script lang="ts" name="Order" setup>
import {
  listOrder,
  getOrder,
  delOrder,
  addOrder,
  updateOrder,
} from "@/api/shop/order";
import { getUserCoupon } from "@/api/shop/coupon";
import { listService } from "@/api/shop/service";
import { listEmployee } from "@/api/shop/employee";
import useUserStore from "@/store/modules/user";
import { getCurrentInstance, ref, reactive, watch, toRefs } from "vue";
import { ArrowDown } from "@element-plus/icons-vue";
const { proxy } = getCurrentInstance();
const userStore = useUserStore();
const orderList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");

const data = reactive({
  form: {},
  serviceTable: [],
  couponList: [],
  employeeList: [],
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    userId: null,
    userName: null,
    paymoney: null,
    paymentType: null,
    orderStart: null,
    orderOver: null,
    orderPause: null,
    serviceName: null,
    orderStatus: null,
    couponId: null,
    couponPrice: null,
    payStatus: null,
    payTime: null,
    shopName: null,
    employeeId: null,
  },
  queryServiceParams: {
    pageNum: 1,
    pageSize: 10,
    serviceName: null,
    serviceCategory: null,
    serviceDetails: null,
    servicePic: null,
    serviceTime: null,
    servicePrice: null,
    sold: null,
    shopName: null,
    launchTime: null,
    downTime: null,
    serviceStatus: null,
  },
  queryCouponParams: {
    pageNum: 1,
    pageSize: 10,
    userId: null,
    shopName: null,
  },
  queryEmployeeParams: {
    pageNum: 1,
    pageSize: 10,
    employeeName: null,
    employeeTimeStart: null,
    employeeStatus: "空闲中",
    employeeDesc: null,
    employeePic: null,
    shopName: null,
  },
  rules: {
    userName: [{ required: true, message: "用户名不能为空", trigger: "blur" }],
    userId: [{ required: true, message: "用户名id", trigger: "blur" }],
    paymoney: [
      { required: true, message: "支付金额不能为空", trigger: "blur" },
    ],

    orderStart: [
      { required: true, message: "开始时间不能为空", trigger: "blur" },
    ],
    orderOver: [
      { required: true, message: "结束时间不能为空", trigger: "blur" },
    ],
    orderPause: [
      { required: true, message: "暂停时间不能为空", trigger: "blur" },
    ],
    serviceName: [
      { required: true, message: "服务名称不能为空", trigger: "blur" },
    ],

    couponId: [
      { required: true, message: "优惠劵ID不能为空", trigger: "blur" },
    ],
    couponPrice: [
      { required: true, message: "优惠劵金额不能为空", trigger: "blur" },
    ],
    orderStatus: [
      { required: true, message: "订单状态不能为空", trigger: "blur" },
    ],
    payStatus: [
      { required: true, message: "支付状态不能为空", trigger: "blur" },
    ],
    payTime: [{ required: true, message: "支付时间不能为空", trigger: "blur" }],
    shopName: [{ required: true, message: "店铺名不能为空", trigger: "blur" }],
    employeeId: [
      { required: true, message: "店员ID不能为空", trigger: "blur" },
    ],
  },
});
/* 获取用户选择的服务列表 */
interface Service {
  serviceName: String;
  serviceCategory: String;
  serviceDetails: String;
  servicePic: String;
  serviceTime: String;
  servicePrice: String;
  sold: BigInt;
  shopName: String;
  launchTime: String;
  downTime: String;
  serviceStatus: String;
}
const selectedRows = ref([]);
const handleServiceChange = (val: Service | undefined) => {
  selectedRows.value = val;
  form.value.serviceName = "";
  selectedRows.value.forEach((element) => {
    form.value.serviceName += element.serviceName + ",";
  });
};
/* 获取用户选择的优惠券 */
interface Coupon {
  couponId: BigInt;
  couponPrice: String;
  couponTimeStart: String;
  couponType: String;
  couponDiscount: String;
  couponMin: String;
  couponTimeEnd: String;
  couponTrade: String;
  couponPic: String;
  shopName: String;
}

const currentRow = ref();
const singleTableRef = ref<InstanceType<typeof ElTable>>();
// const popoverVisible= ref(false);
const setCurrent = (row?: User) => {
  singleTableRef.value!.setCurrentRow(row);
};
const handleCurrentChange = (val: Coupon | undefined) => {
  currentRow.value = val;
  form.value.couponId = val.couponId;
};
// const couponTableShow=ref(true)
// function handlePopoverOpen(){
//   popoverVisible.value=true;
// }
function closePopover(){
  // singleTableRef.value.visiable=false;
  // console.log(singleTableRef.value.visiable)
}
/* 获取用户选择的技师 */
interface Employee {
  employeeId: BigInt;
  employeeName: String;
  employeeTimeStart: String;
  employeeStatus: String;
  employeeDesc: String;
  employeePic: String;
  shopName: String;
}
const handleEmployeeChange = (val: Employee | undefined) => {
  //   currentRow.value = val;
  form.value.employeeId = val?.employeeId;
};

/* 选择服务时间段 */
const selectedDate = ref(null);
const selectedTime = ref(null);

// 获取当前时间
const currentTime = new Date();
const currentHour = currentTime.getHours();
const currentMinute = currentTime.getMinutes();
const currentSecond = currentTime.getSeconds();

// 禁用日期选择器中的日期
const currentDate = new Date();
currentDate.setHours(0, 0, 0, 0);

const disabledDate = (date) => {
  return date.getTime() < currentDate.getTime();
};

// 禁用小时
const disabledHours = () => {
  const hours = [];
  // 如果选择的日期为当前日期，则根据当前时间来禁用小时
  if (selectedDate.value && selectedDate.value.getTime() === currentDate.getTime()) {
    for (let i = 0; i < currentHour; i++) {
      hours.push(i);
    }
  }
  if(selectedDate.value && selectedDate.value.getTime() >= currentDate.getTime()){
    for(let j=3;j<8;j++){
    hours.push(j);
  }
  }
  
  return hours;
};

// 禁用分钟
const disabledMinutes = (hour) => {
  if (hour === currentHour) {
    const minutes = [];
    for (let i = 0; i < currentMinute; i++) {
      minutes.push(i);
    }
    return minutes;
  }
  return [];
};

// 禁用秒钟
const disabledSeconds = (hour, minute) => {
  if (hour === currentHour && minute === currentMinute) {
    const seconds = [];
    for (let i = 0; i < currentSecond; i++) {
      seconds.push(i);
    }
    return seconds;
  }
  return [];
};

const {
  queryParams,
  form,
  couponList,
  serviceTable,
  employeeList,
  queryServiceParams,
  queryCouponParams,
  queryEmployeeParams,
  rules,
} = toRefs(data);
/** 查询订单列表 */
function getList() {
  loading.value = true;
  queryParams.value.userName = userStore.name;
  listOrder(queryParams.value).then((response) => {
    orderList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    orderId: null,
    userName: null,
    paymoney: null,
    paymentType: null,
    createTime: null,
    orderStart: null,
    orderOver: null,
    orderPause: null,
    serviceName: null,
    orderStatus: null,
    couponId: null,
    couponPrice: null,
    payStatus: null,
    payTime: null,
    shopName: null,
    employeeId: null,
    updateTime: null,
  };
  proxy.resetForm("orderRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map((item) => item.orderId);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
/* function handleAdd() {
    reset();
    open.value = true;
    title.value = "添加订单";
} */

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  queryServiceParams.value.shopName = row.shopName;
  getShopService();
  queryCouponParams.value.userId = userStore.id;
  queryCouponParams.value.shopName = row.shopName;
  getUserOwnCoupon(queryCouponParams.value);
  queryEmployeeParams.value.shopName = row.shopName;
  getFreeEmployee(queryEmployeeParams.value);
  const _orderId = row.orderId || ids.value;
  getOrder(_orderId).then((response) => {
    form.value = response.data;
    open.value = true;
    title.value = "修改订单";
  });
}
/**查询店铺上架中的服务 */
function getShopService() {
  listService(queryServiceParams.value)
    .then((response) => {
      serviceTable.value = response.rows;
    })
    .catch((error) => {
      console.log(error);
    });
}
/* 查询用户在对应店铺拥有的优惠券 */
function getUserOwnCoupon() {
  console.log(queryCouponParams.value)
  getUserCoupon(queryCouponParams.value)
    .then((response) => {
      couponList.value = response.rows;
      console.log(couponList.value)
    })
    .catch((error) => {
      console.log(error);
    });
}
/* 查询空闲中的技师 */
function getFreeEmployee() {
  listEmployee(queryEmployeeParams.value).then((response) => {
    employeeList.value = response.rows;
    console.log(response.rows);
  });
}
/* 获取选中技师优惠券数据 */
function handleCouponChange(selection) {}
/** 提交按钮 */
function submitForm() {
  proxy.$refs["orderRef"].validate((valid) => {
    if (valid) {
      if (form.value.orderId != null) {
        updateOrder(form.value).then((response) => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addOrder(form.value).then((response) => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _orderIds = row.orderId || ids.value;
  proxy.$modal
    .confirm('是否确认删除订单编号为"' + _orderIds + '"的数据项？')
    .then(function () {
      return delOrder(_orderIds);
    })
    .then(() => {
      getList();
      proxy.$modal.msgSuccess("删除成功");
    })
    .catch(() => {});
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download(
    "shop/order/export",
    {
      ...queryParams.value,
    },
    `order_${new Date().getTime()}.xlsx`
  );
}

getList();
</script>
<style scoped>
.el-dropdown-link {
  cursor: pointer;
  color: var(--el-color-primary);
  display: flex;
  align-items: center;
}

.el-button {
  border: none;
}
.coupon {
  width: 60px;
  height: 40px;
}
.time-picker-container {
  display: flex;
  align-items: center;
}

.coupon-option {
  display: flex;
  align-items: center;
  gap: 12px;
}

.coupon-price {
  color: #f56c6c;
  font-size: 16px;
  font-weight: bold;
}

:deep(.el-table) {
  border-radius: 4px;
  border: 1px solid #ebeef5;
}

:deep(.el-select-dropdown__item) {
  height: 50px;
  line-height: 50px;
}

</style>
